import React, { useState, useEffect, useMemo } from 'react';
import Head from 'next/head';
import { Row, Col, List, Input, Select, Spin } from 'antd';
const { Search } = Input;
const { Option } = Select;
import { createFromIconfontCN } from '@ant-design/icons';
import Router from 'next/router';
import Header from '../components/header';
import Footer from '../components/footer';
import Bgc from '../components/bgc';
import cssArticle from '../static/style/pages/article.scss';
import API from '../util/apiUrl';
import iconUrl from '../util/iconUrl';

const IconFont = createFromIconfontCN({
  scriptUrl: iconUrl,
});

const Article = (props) => {
  console.log('article props', props, 'cssArticle', cssArticle);
  //   const [colorList, setColorList] = useState([
  //     '#FF5E3A',
  //     '#FF2A68',
  //     '#EF4DB6',
  //     '#C643FC',
  //     '#1AD6FD',
  //     '#1D62F0',
  //     '#FFCC00',
  //     '#FF9500',
  //   ]);
  const [bgcUrl, setBgcUrl] = useState({});
  const [isShowImg, setIsShowImg] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  // const [articleList, setArticleList] = useState(
  //   [...props.list[1].allRes] || []
  // );
  const [articleList, setArticleList] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  // 获取压缩图片地址
  const getRecommendList = (list) => {
    let recommendList = list.map((i) => {
      let ysimg;
      if (i.img) {
        ysimg = i.img.split('.');
        ysimg[ysimg.length - 2] = ysimg[ysimg.length - 2] + 'ys';
        ysimg = ysimg.join('.');
      } else {
        ysimg = null;
      }
      return {
        ...i,
        ysimg,
      };
    });
    return recommendList
  };

  const ShowImg = ({ img }) => {
    console.log('img', img);
    return (
      <div
        className={cssArticle.showImg}
        onClick={() => {
          setIsShowImg('');
        }}
      >
        <img src={img} alt="" />
      </div>
    );
  };

  useEffect(() => {
    showTop();
    document.addEventListener('scroll', scrollListener);
    
    if (props.list[1]&&props.list[1].allRes) {
      setArticleList(getRecommendList(props.list[1].allRes)) 
    }

    return () => {
      document.removeEventListener('scroll', scrollListener);
    };
  }, []);

  // 获取对应技术类别的列表
  const skillTypeChange = async (id) => {
    console.log('skillType id', id);
    setIsLoading(true);
    if (id == 0) {
      setArticleList(getRecommendList([...props.list[1].allRes]) );
      setIsLoading(false);
    } else {
      try {
        let res = await API.getSkillTypeList(id);
        console.log('res', res);
        setArticleList(getRecommendList(res.data) );

        scrollListener()
        
        setIsLoading(false);
      } catch (error) {
        console.log('err', error);
        setIsLoading(false);
      }
    }
  };

  // 获取关键词列表
  const searchKeywordList = async (value)=>{
    console.log('value',value)
    setIsLoading(true);
    if(!value){
      setArticleList(getRecommendList([...props.list[1].allRes]) );
      setIsLoading(false)
    }else if(value===searchValue){
      // 搜索与上次一样
      setIsLoading(false)
      return false
    }else{
      setSearchValue(value)

      API.getKeywordList(value).then(res=>{
        console.log('res key',res)
        setArticleList(getRecommendList(res.data) );
        setIsLoading(false)
      }).catch(err=>{
        console.log('err',err)
        setIsLoading(false)
      })
    }

  }

  //   查看详情
  const lookDetail = (id) => {
    console.log('查看详情', id);
    Router.push('/detail?id=' + id);
  };

  // 直接显示顶部
  const showTop = () => {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  };

  // 滚动到文章位置
  const scrollTo = (id) => {
    let domY =
      document.getElementById(id).getBoundingClientRect().top -
      55 +
      window.pageYOffset;
    window.scrollTo({
      top: domY,
      behavior: 'smooth', //  smooth(平滑滚动),instant(瞬间滚动),默认auto
    });
  };

  // item动画
  const scrollListener = () => {
    let winHeight = window.innerHeight;
    let doms = document.querySelectorAll('.listItem');
    // console.log('doms',doms.length)
    doms.forEach((i, idx) => {
      if ((i.getBoundingClientRect().top-(i.offsetHeight/3)) < winHeight) {
        i.style.transform = 'scale(1)';
      } else {
        i.style.transform = 'scale(0)';
      }
    });
  };
  return (
    <>
    {isShowImg ? <ShowImg img={isShowImg} /> : null}
      <Head>
        <title>yzyの博客-文章</title>
        <link
          rel="shortcut icon"
          href="../static/img/bitbug_favicon.ico"
          type="image/x-icon"
        />
      </Head>

      <Header
        getBgcUrl={(data) => {
          setBgcUrl(data);
        }}
        current="2"
      />

      <Bgc
        bgcUrl={bgcUrl}
        scrollTo={(id) => {
          scrollTo(id);
        }}
        btns={[
          {
            name: '查看文章',
            id: 'articleListTitle',
            icon: 'icon-image-text',
          },
        ]}
      />
      {/* <div
        className={cssArticle.bgcImg}
        // style={{ backgroundImage: `url(${bgcUrl.carousel_img})` }}
      >
        <div className={cssArticle.content}>
          <div className={cssArticle.title}>
            <h3>{bgcUrl.name}</h3>
            <span>一些文字..</span>
          </div>
        </div>
      </div> */}

      <div className={cssArticle.common}>
        <Row className={cssArticle.comm_main} justify="center">
          <Col className={cssArticle.comm_home} span={24}>
            <div className={cssArticle.content} id="content">
              <div className={cssArticle.recommend}>
                <div className={cssArticle.head}>
                  <div className={cssArticle.title} id="articleListTitle">
                    <div className={cssArticle.num}>
                      文章数量: <i>{props.list[1].allRes.length}</i> 篇
                    </div>
                    <div className={cssArticle.type}>
                      技术类别:
                      <Select
                        defaultValue={0}
                        style={{
                          width: 120,
                          marginLeft: 8,
                          verticalAlign: 'middle',
                        }}
                        onChange={skillTypeChange}
                      >
                        {props.list[2].skillType.map((i) => (
                          <Option value={i.id} key={i.id}>
                            {i.name}
                          </Option>
                        ))}
                      </Select>
                    </div>
                  </div>
                  <Search
                    className={cssArticle.search}
                    placeholder="搜索关键词或句"
                    onSearch={searchKeywordList}
                    style={{ width: '100%' }}
                  />
                </div>
                <div className={cssArticle.articleList}>
                  {isLoading ? (
                    <Spin />
                  ) : (
                    <List
                      size="large"
                      //   header={<div>Header</div>}
                      //   footer={<div>Footer</div>}
                      dataSource={articleList}
                      renderItem={(item) => (
                        <List.Item>
                          <div className={cssArticle.list+' listItem'}>
                            <div
                              className={cssArticle.title}
                              onClick={() => {
                                lookDetail(item.id);
                              }}
                            >
                              {item.title}
                            </div>
                            <div className={cssArticle.msg}>
                              <span>
                                <IconFont type="icon-shijian" />
                                {item.updateTime}
                              </span>
                              <span>
                                <IconFont type="icon-shaixuan" />
                                {props.list[2].skillType.find(
                                  (i) => i.id == item.skillTypeId
                                )
                                  ? props.list[2].skillType.find(
                                      (i) => i.id == item.skillTypeId
                                    ).name
                                  : '未知'}
                              </span>
                              <span>
                                <IconFont type="icon-hot" />
                                {item.people||'0'}人
                              </span>
                            </div>
                            {item.img ? (
                              <div
                              onClick={() => {
                                setIsShowImg(item.img);
                              }}
                                className={cssArticle.img}
                                style={{ backgroundImage: `url('${item.ysimg}')` }}
                              ></div>
                            ) : (
                              ''
                            )}
                            <div className={cssArticle.synopsis}>
                              {item.synopsis}
                            </div>
                            <div
                              className={cssArticle.lookContent}
                              onClick={() => {
                                lookDetail(item.id);
                              }}
                            >
                              <IconFont type="icon-dingdan" />
                              查看全文&gt;
                            </div>
                          </div>
                        </List.Item>
                      )}
                    />
                  )}
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <Footer />
    </>
  );
};

Article.getInitialProps = async () => {
  let res = await API.getHomeArticle();
  // console.log('res000', res);
  return { list: res.data };
};

export default Article;
